package lee.study.Data_Struct.Hash;

class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array = new Node[10];
    public int usedSize;

    public void put(int key, int val) {//放
        int index = key % array.length;//找到数组的Index

        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {//遍历完如果有相同的key就把val值更新一下
                cur.val = val;
                return;
            }
        }
        Node node = new Node(key, val);//在index对应的链表中未找到key值
        node.next = array[index];
        array[index] = node;
        this.usedSize++;

        if (loadFactor() > 0.75) {
            resize();
        }
    }

    public void resize() {
        //扩容需要进行重新哈希       11 % 10 = 1 index  11 % 20= 11 index
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {

            Node cur = array[i];
            while (cur != null) {
                int newIndex = cur.key % newArray.length;//拿到新的数组对应的Index
                //1、cur.key % newArray.length   index
                //2、头插法的形式，插入到newArray[index]
                Node curNext = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }


    public double loadFactor() {//负载因子
        return this.usedSize * 1.0 / this.array.length;
    }

    public int getValue(int key) {
        int index = key % array.length;
        Node cur = array[index];

        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            } else {
                cur = cur.next;
            }
        }
        return -1;
    }
}

public class MyHashMap {
    public static void main(String[] args) {
        HashBuck hashBuck = new HashBuck();
        for (int i = 1; i < 8; i++) {
            hashBuck.put(i, i);
        }
        hashBuck.put(11, 121);
        System.out.println(hashBuck.getValue(11));
    }
}
